package com.atguigu.lease.web.admin.custom.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * ClassName: AuthenticationInterceptor
 * Package: com.atguigu.lease.web.admin.custom.interceptor
 * Description:
 *
 * @Author: tiantian
 * @Create: 2024/10/9 - 23:30
 * @Version: v1.0
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    //校验Token，必须在处理请求之前，去完成校验，处理请求都结束了，就没有意义了

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //三个参数之一：HttpServletRequest request:获取用户发送请求的全部信息
        //三个参数之一：HttpServletResponse response：对响应信息做一个修改
        //三个参数之一：Object handler：拦截的controller方法，可以根据反射的手段来获取controller方法当中的一些信息：注解，参数等等
        //true：放行，请求继续往下执行，false：请求就到此为止了
        //一般会将token放在请求头当中
        String token = request.getHeader("access_token");

        Claims claims = JwtUtil.parseToken(token);

        Long userId = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);
        LoginUserContext.setLoginUser(new LoginUser(userId, username));
        //如果Token在解析的过程中一切正常，就顺利执行下去，遇到任何问题就会抛出异常，方法运行也就中断了
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.clear();
    }
}
